package xyfcoco.com.my_plugins

import android.app.Activity
import android.util.Log
import androidx.annotation.NonNull

import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import android.util.TimeUtils
import android.widget.Toast
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import java.util.*

class AlarmEvent {
    var title: String? = null
    var description: String? = null
    var hour = 0
    var minutes = 0
    var days: ArrayList<Integer>? = null

    companion object {
        fun parse(json: Map<String?, Object>): AlarmEvent {
            val event = AlarmEvent()
            event.title = json["title"]
            event.description = json["description"]
            event.hour = json["hour"]
            event.minutes = json["minutes"]
            event.days = json["days"] as ArrayList<Integer?>
            return event
        }
    }
}

/** MyPluginsPlugin */
class MyPluginsPlugin : FlutterPlugin, MethodCallHandler , ActivityAware {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private lateinit var channel: MethodChannel

    /**
     * 注册对象
     */
    private lateinit var mActivity: Activity

    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "my_plugins")
        channel.setMethodCallHandler(this)
    }

    override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
        if (call.method == "getPlatformVersion") {
            result.success("Android ${android.os.Build.VERSION.RELEASE}")
        } else if (call.method == "sendCalender") {
            addNotify(call.argument("time"), call.argument("title"), call.argument("desc"))
            result.success("发送成")
        } else if(call.method == "add2Alarm"){
            add2Alarm(AlarmEvent.parse(call.arguments as Map<String?, Object?>))
            result.success("success")
        } else {
            result.notImplemented()
        }
    }

    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }


    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        mActivity = binding.activity
    }

    override fun onDetachedFromActivityForConfigChanges() {

    }

    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
        TODO("Not yet implemented")
    }

    override fun onDetachedFromActivity() {
        TODO("Not yet implemented")
    }

//    添加闹钟提醒
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private fun add2Alarm(event: AlarmEvent) {
        val intent: Intent = Intent(AlarmClock.ACTION_SET_ALARM) //闹钟的小时
                .putExtra(AlarmClock.EXTRA_HOUR, event.hour) //闹钟的分钟
                .putExtra(AlarmClock.EXTRA_MINUTES, event.minutes) //响铃时提示的信息
                .putExtra(AlarmClock.EXTRA_MESSAGE, event.title) //用于指定该闹铃触发时是否振动
                .putExtra(AlarmClock.EXTRA_VIBRATE, true) //一个 content: URI，用于指定闹铃使用的铃声，也可指定 VALUE_RINGTONE_SILENT 以不使用铃声。
                //如需使用默认铃声，则无需指定此 extra。
                //  .putExtra(AlarmClock.EXTRA_RINGTONE, ringtoneUri)
                //一个 ArrayList，其中包括应重复触发该闹铃的每个周日。
                // 每一天都必须使用 Calendar 类中的某个整型值（如 MONDAY）进行声明。
                //对于一次性闹铃，无需指定此 extra
                .putExtra(AlarmClock.EXTRA_DAYS, event.days) //如果为true，则调用startActivity()不会进入手机的闹钟设置界面
                .putExtra(AlarmClock.EXTRA_SKIP_UI, true)
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
         mActivity.startActivity(intent)
    }

    /**
     * 添加日历提醒
     *
     * @param date 日期
     * @param msg  提醒内容
     */
    fun addNotify(date: Long?, title: String?, msg: String?) {
        if (date==null || msg == null|| title==null){
            return
        }

        val calendarEvent = CalendarEvent(
                title,
                msg,
                "",
                date,
                date + 60000,
                0)

        // 添加事件
        val result: Int = CalendarUtil.addCalendarEvent(mActivity, calendarEvent)
        if (result == 0) {
            Toast.makeText(mActivity, "添加日历提醒成功", Toast.LENGTH_LONG).show()
        } else {
            Toast.makeText(mActivity, "添加日历提醒失败", Toast.LENGTH_LONG).show()
        }
    }
}
